package com.nativetalk.controller.app.data;

import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.course.TdNtCoursePictureList;
import com.nativetalk.bean.course.TsNtCourseInfoDetail;
import com.nativetalk.bean.course.catalog.TdNtCourseCatalog;
import com.nativetalk.bean.member.*;
import com.nativetalk.bean.member.course.TdNtMembCourseDetail;
import com.nativetalk.bean.website.TsNtWebSiteConfIndex;
import com.nativetalk.common.Constants;
import com.nativetalk.common.Lang;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.oss.OssUtil;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.common.util.JsonUtil;
import com.nativetalk.common.util.MemcachedKey;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.service.member.course.search.MembCourseSearchService;
import com.nativetalk.service.member.search.MemberSearchService;
import com.nativetalk.service.member.update.MemberUpdateService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lizhun on 15/12/9.
 */
@Controller
public class DataController {

    private static Logger logger = Logger.getLogger(DataController.class);
    @Resource
    private MemberUpdateService memberUpdateService;
    @Resource
    private MemberSearchService memberSearchService;
    @Resource
    private MembCourseSearchService membCourseSearchService;

    /**
     * @return RetInfo
     * @Purpose 我的
     * @version 1.0
     * @time 2015-12-27
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/token/member/me", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo me(@RequestHeader(value = "token", required = true) String token) {
        try {
            //打印入参
            logger.info(Constants.prefix_in);

            RetInfo retInfo = new RetInfo();
            Map<String, Object> map = new HashMap<>();
            TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
            map.put("memb_head_portrait", tdNtMember.getMemb_head_portrait());
            map.put("memb_name", tdNtMember.getMemb_name());
            map.put("memb_phone", tdNtMember.getMemb_phone());
            map.put("memb_sex", tdNtMember.getMemb_sex());
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取我的成功");
            retInfo.setObj(map);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @return RetInfo
     * @Purpose 我的
     * @version 2.0
     * @time 2015-12-27
     * @author lizhun
     */
    @RequestMapping(value = "/app/2/token/member/me/Deprecated", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo meTwo(@RequestHeader(value = "token", required = true) String token) {
        try {
            //打印入参
            logger.info(Constants.prefix_in);

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = MemcachedUtils.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            RetInfo retInfo = new RetInfo();
            Map<String, Object> map = new HashMap<>();
            map.put("memb_head_portrait", tdNtMember.getMemb_head_portrait());
            map.put("memb_name", tdNtMember.getMemb_name());
            map.put("memb_phone", tdNtMember.getMemb_phone());
            map.put("memb_sex", tdNtMember.getMemb_sex());
            TdNtMembCourseDetail tdNtMembCourseDetail = membCourseSearchService.findTdNtMembCourseDetailByMembId(tdNtMember.getMemb_id());
            if (tdNtMembCourseDetail != null) {
                Map<String, TsNtCourseInfoDetail> tsNtCourseInfoDetailMap = (Map<String, TsNtCourseInfoDetail>) MemcachedUtils.get(MemcachedKey.tsNtCourseInfoDetailMap);
                TsNtCourseInfoDetail tsNtCourseInfoDetail = tsNtCourseInfoDetailMap.get(tdNtMembCourseDetail.getCou_id() + "");
                map.put("cou_name", tsNtCourseInfoDetail.getCou_name());
                Map<String, List<TdNtCoursePictureList>> tdNtCourseBannerListMap = (Map<String, List<TdNtCoursePictureList>>) MemcachedUtils.get(MemcachedKey.tdNtCourseBannerListMap);


                List<TdNtCoursePictureList> tdNtCoursePictureLists = tdNtCourseBannerListMap.get(tdNtMembCourseDetail.getCou_id() + "");

                if (tdNtCoursePictureLists != null && tdNtCoursePictureLists.size() != 0) {
                    map.put("picture", tdNtCoursePictureLists.get(0).getImg_url());
                }

                Map<String, List<TdNtCourseCatalog>> tdNtCourseCatalogMap = (Map<String, List<TdNtCourseCatalog>>) MemcachedUtils.get(MemcachedKey.tdNtCourseCatalogMap);
                List<TdNtCourseCatalog> tdNtCourseCatalogs = tdNtCourseCatalogMap.get(tdNtMembCourseDetail.getCou_id() + "");
                int size = 0;
                for (int i = 0; i < tdNtCourseCatalogs.size(); i++) {
                    if (i < (tdNtCourseCatalogs.size() - 1)) {
                        if (tdNtMembCourseDetail.getStudy_page() >= tdNtCourseCatalogs.get(i).getEnd_page() && tdNtMembCourseDetail.getStudy_page() >= tdNtCourseCatalogs.get(i + 1).getEnd_page()) {
                            size = i + 1;
                            break;
                        }
                    } else {
                        if (tdNtMembCourseDetail.getStudy_page() >= tdNtCourseCatalogs.get(i).getEnd_page()) {
                            size = i + 1;
                            break;
                        }
                    }


                }
                map.put("size", size);
                map.put("cou_id", tdNtMembCourseDetail.getCou_id());
                map.put("cate_id", tsNtCourseInfoDetail.getCate_id());
                map.put("totalSize", tdNtCourseCatalogs.size());
                map.put("course", 0);
            } else {
                retInfo.setTip("您还没有开始学习");
                map.put("course", 1);
            }

            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setObj(map);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @return RetInfo
     * @Purpose 个人资料
     * @version 1.0
     * @time 2015-12-27
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/token/member/data", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo data(@RequestHeader(value = "token", required = true) String token) {
        RetInfo retInfo = new RetInfo();
        Map<String, Object> map = new HashMap<>();
        TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
        map.put("memb_head_portrait", tdNtMember.getMemb_head_portrait());
        map.put("memb_name", tdNtMember.getMemb_name());
        map.put("memb_phone", tdNtMember.getMemb_phone());
        map.put("memb_sex", tdNtMember.getMemb_sex());
        map.put("memb_birthday", tdNtMember.getMemb_birthday());
        map.put("memb_synopsis", tdNtMember.getMemb_synopsis());
        retInfo.setMark(ValidationMessages.getValue("MARKYES"));
        retInfo.setTip("获取个人成功");
        retInfo.setObj(map);
        return retInfo;
    }

    /**
     * @return RetInfo
     * @Purpose 修改名称
     * @version 1.0
     * @time 2015-12-27
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/token/member/updateMembName", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo updateMembName(@Valid @RequestBody TdNtMemberName tdNtMemberName, BindingResult result,
                                  @RequestHeader(value = "token", required = true) String token) {
        RetInfo retInfo = new RetInfo();
        if (result.hasErrors()) {
            List<FieldError> err = result.getFieldErrors();
            FieldError fe = err.get(0);
            retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
            retInfo.setTip(fe.getDefaultMessage());
        } else {
            TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
            tdNtMember.setMemb_name(tdNtMemberName.getMemb_name());
            retInfo = memberUpdateService.updateTdNtMember(tdNtMember);
        }
        return retInfo;
    }

    /**
     * @return RetInfo
     * @Purpose 修改性别
     * @version 1.0
     * @time 2015-12-27
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/token/member/updateMembSex", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo upateMembSex(@Valid @RequestBody TdNtMemberSex tdNtMemberSex, BindingResult result,
                                @RequestHeader(value = "token", required = true) String token) {
        RetInfo retInfo = new RetInfo();
        if (result.hasErrors()) {
            List<FieldError> err = result.getFieldErrors();
            FieldError fe = err.get(0);
            retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
            retInfo.setTip(fe.getDefaultMessage());
        } else {
            TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
            tdNtMember.setMemb_sex(tdNtMemberSex.getMemb_sex());
            retInfo = memberUpdateService.updateTdNtMember(tdNtMember);
        }
        return retInfo;
    }

    /**
     * @return RetInfo
     * @Purpose 修改简介
     * @version 1.0
     * @time 2015-12-27
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/token/member/upateMembSynopsis", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo upateMembSynopsis(@Valid @RequestBody TdNtMemberSynopsis tdNtMemberSynopsis, BindingResult result,
                                     @RequestHeader(value = "token", required = true) String token) {
        RetInfo retInfo = new RetInfo();
        if (result.hasErrors()) {
            List<FieldError> err = result.getFieldErrors();
            FieldError fe = err.get(0);
            retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
            retInfo.setTip(fe.getDefaultMessage());
        } else {
            TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
            tdNtMember.setMemb_synopsis(tdNtMemberSynopsis.getMemb_synopsis());
            retInfo = memberUpdateService.updateTdNtMember(tdNtMember);
        }
        return retInfo;
    }

    /**
     * @return RetInfo
     * @Purpose 修改生日
     * @version 1.0
     * @time 2015-12-27
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/token/member/upateMembBirthday", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo upateMembBirthday(@Valid @RequestBody TdNtMemberBirthday tdNtMemberBirthday, BindingResult result,
                                     @RequestHeader(value = "token", required = true) String token) {
        RetInfo retInfo = new RetInfo();
        if (result.hasErrors()) {
            List<FieldError> err = result.getFieldErrors();
            FieldError fe = err.get(0);
            retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
            retInfo.setTip(fe.getDefaultMessage());
        } else {
            TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
            tdNtMember.setMemb_birthday(tdNtMemberBirthday.getMemb_birthday());
            tdNtMember.setMemb_ages(CommonUtil.getAge(new Date(tdNtMemberBirthday.getMemb_birthday().getTime())));
            retInfo = memberUpdateService.updateTdNtMember(tdNtMember);
        }
        return retInfo;
    }

    /**
     * @return RetInfo
     * @Purpose 修改密码
     * @version 1.0
     * @time 2015-12-27
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/token/member/upateMembPsd", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo upateMembPsd(@Valid @RequestBody TdNtMemberPsd tdNtMemberPsd, BindingResult result,
                                @RequestHeader(value = "token", required = true) String token) {
        RetInfo retInfo = new RetInfo();
        if (result.hasErrors()) {
            List<FieldError> err = result.getFieldErrors();
            FieldError fe = err.get(0);
            retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
            retInfo.setTip(fe.getDefaultMessage());
        } else {
            TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
            retInfo = memberUpdateService.updateTdNtMemberPsd(tdNtMemberPsd, tdNtMember);
        }
        return retInfo;
    }

    /**
     * @return RetInfo
     * @Purpose 查看个人余额
     * @version 1.0
     * @time 2015-12-28
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/token/member/balance", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo balance(@RequestHeader(value = "token", required = true) String token) {
        TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
        return memberSearchService.findMemberBalance(tdNtMember.getMemb_id());
    }

    /**
     * @return RetInfo
     * @Purpose 查看个人余额
     * @version 1.0
     * @time 2015-12-28
     * @author lizhun
     */
    @RequestMapping(value = "/app/3/token/member/balance", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo balanceThree(@RequestHeader(value = "token", required = true) String token) {
        TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
        return memberSearchService.findMemberBalanceThree(tdNtMember.getMemb_id());
    }

    /**
     * @return RetInfo
     * @Purpose 邀请码
     * @version 1.0
     * @time 2015-12-30
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/token/member/invitation", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo invitation(@RequestHeader(value = "token", required = true) String token) {
        RetInfo retInfo = new RetInfo();
        Map<String, Object> map = new HashMap<>();
        TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
        map.put("invite_code", tdNtMember.getMemb_invite_code());
        Map<String, TsNtWebSiteConfIndex> tsNtWebSiteConfIndexMap = (Map<String, TsNtWebSiteConfIndex>) MemcachedUtils.get(MemcachedKey.tsNtWebSiteConfIndexMap);
        map.put("invite_picture", tsNtWebSiteConfIndexMap.get("1").getData_value());
        map.put("invite_synopis", tsNtWebSiteConfIndexMap.get("2").getData_value());
        map.put("invite_url", "http://www.baidu.com");
        map.put("invite_title", "外教君");
        retInfo.setMark(ValidationMessages.getValue("MARKYES"));
        retInfo.setTip("获取邀请信息成功");
        retInfo.setObj(map);
        return retInfo;
    }

    /**
     * @param commonsMultipartFile
     * @return RetInfo
     * @Purpose 更换头像
     * @version 1.0
     * @time 2015-12-24
     * @author lizhun
     */
    @RequestMapping(value = "/app/1/token/member/headPortrait", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public RetInfo headPortrait(@RequestParam(value = "headPortrait", required = true) CommonsMultipartFile commonsMultipartFile,
                                @RequestHeader(value = "token", required = true) String token) throws IOException {
        RetInfo retInfo = new RetInfo();
        TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
        if (commonsMultipartFile != null && commonsMultipartFile.getSize() > 3145728) {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip("头像超过3M");
        } else {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(commonsMultipartFile.getSize());
            String headPortrait = Constants.FILE + "/" + Constants.FILEIMG + "/image/member/" + tdNtMember.getMemb_phone() + "/"
                    + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis())) + "2" + commonsMultipartFile.getOriginalFilename().substring(commonsMultipartFile.getOriginalFilename().lastIndexOf("."));
            OssUtil.uploadInputStream(commonsMultipartFile.getInputStream(), objectMetadata, headPortrait);
            tdNtMember.setMemb_head_portrait(headPortrait);
            retInfo = memberUpdateService.updateTdNtMember(tdNtMember);
        }
        return retInfo;
    }

    /**
     * @return RetInfo
     * @Purpose 邀请码
     * @version 2.0
     * @time 2015-12-30
     * @author lizhun
     */
    @RequestMapping(value = "/app/2/token/member/invitation", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo invitationTwo(@RequestHeader(value = "token", required = true) String token) {
        RetInfo retInfo = new RetInfo();
        Map<String, Object> map = new HashMap<>();
        TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);

        Map<String, TsNtWebSiteConfIndex> tsNtWebSiteConfIndexMap = (Map<String, TsNtWebSiteConfIndex>) MemcachedUtils.get(MemcachedKey.tsNtWebSiteConfIndexMap);
        map.put("share", tsNtWebSiteConfIndexMap.get("12").getData_value());
        map.put("invite_code", tdNtMember.getMemb_invite_code());
        map.put("invite_picture", tsNtWebSiteConfIndexMap.get("1").getData_value());
        map.put("invite_synopis", tsNtWebSiteConfIndexMap.get("2").getData_value());
        map.put("invite_url", tsNtWebSiteConfIndexMap.get("14").getData_value() + "?invite_code="
                + tdNtMember.getMemb_invite_code());
        map.put("invite_title", tsNtWebSiteConfIndexMap.get("13").getData_value());
        map.put("share_picutre", tsNtWebSiteConfIndexMap.get("15").getData_value());
        map.put("share_content", tsNtWebSiteConfIndexMap.get("16").getData_value());
        retInfo.setMark(ValidationMessages.getValue("MARKYES"));
        retInfo.setTip("获取邀请信息成功");
        retInfo.setObj(map);
        return retInfo;
    }
}


